import React, {useEffect} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import { View, Image, Button, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import {loginAction} from '../../actions/user'
import './index.scss'
import {UserProps} from '../../reducers/user'
import {ReduxStateProps} from '../../reducers'

interface ResultProps {
  errCode: string;
  errMsg: string;
  user: UserProps;
}

interface ResProps extends Taro.cloud.CallFunctionResult  {
  result: ResultProps;
}

export default function me() {
  const dispatch = useDispatch()
  const user = useSelector((state: ReduxStateProps) => state.user)

  useEffect(() => {
    // login()
  }, [])

  function loginHandler(nickName, avatarUrl) {
    console.log('发起请求：', nickName, avatarUrl)
    Taro.cloud.callFunction({
      name: 'tieUser',
      data: {
        type: 'login',
        nickName: nickName,
        avatarUrl: avatarUrl
      }
    })
    .then(function (res: ResProps) {
      console.log(res)
      dispatch(loginAction({
        nickName: res.result.user.nickName,
        avatarUrl: res.result.user.avatarUrl,
        userId: res.result.user.userId
      }))
    })
    .catch(err => {
      console.log(err)
    })
  }

  const getUserInfoHandler = () => {
    Taro.getUserProfile({
      desc: '登陆', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('获取用户信息：', res)
        loginHandler(res.userInfo.nickName, res.userInfo.avatarUrl)
      }
    })
    
  }
  return (
    <View className='me'>
      <View className='me-info'>
        {user.nickName ? (
          <>
            <Image src={user.avatarUrl} mode="aspectFill" className="user_avatar"></Image>
            <View className='me-info-text'>
              <View className='me-nickname'>{user.nickName}</View>
              <View className='me-points'>积分</View>
            </View>
          </>
        ) : <Button onClick={getUserInfoHandler} style="width: 100%;">登录</Button>}
        
      </View>
    </View>
  )
}
